package com.sec.etech.employeesync.enums;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployee;
import com.sec.etech.employeesync.mapper.OrgEmployeeMapper;
import com.sec.etech.employeesync.service.SyncDataContext;
import org.apache.commons.lang3.StringUtils;
import org.openbpm.base.api.exception.BusinessException;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;

public enum SyncType {
    SINGLE(syncData -> {
        if (syncData.getNewList().size() != 1) {
            throw new BusinessException("无法从SAP查询到该员工");
        }

        OrgEmployee orgEmployee = syncData.getOrgEmployeeMapper().selectOne(Wrappers.<OrgEmployee>lambdaQuery()
                .eq(OrgEmployee::getAccount, syncData.getNewList().get(0).getAccount()));

        if (orgEmployee == null) {
            throw new BusinessException("无法从本地查询到该员工");
        }

        return Collections.singletonList(orgEmployee);
    }),

    COMPANY(syncData -> {
        String companyCode = syncData.getCompanyCode();
        OrgEmployeeMapper orgEmployeeMapper = syncData.getOrgEmployeeMapper();

        if (StringUtils.isBlank(companyCode)) {
            throw new BusinessException("公司同步模式下，必须提供公司代码");
        }

        // 根据公司代码查询员工
        return orgEmployeeMapper.queryEmployeeByCompany(companyCode);
    }),

    FULL(syncData -> syncData.getOrgEmployeeMapper().selectList(null));

    private final Function<SyncDataContext, List<OrgEmployee>> syncFunction;

    SyncType(Function<SyncDataContext, List<OrgEmployee>> syncFunction) {
        this.syncFunction = syncFunction;
    }

    public List<OrgEmployee> sync(SyncDataContext syncData) {
        return syncFunction.apply(syncData);
    }
}
